package com.hbnu.net;

import java.net.DatagramPacket;
import java.net.DatagramSocket;


//循环接收
public class UDPReceiveThread implements Runnable{

    private DatagramSocket datagramSocket;

    public UDPReceiveThread(DatagramSocket datagramSocket) {
        this.datagramSocket = datagramSocket;
    }

    @Override
    public void run() {
        while(true){
            //接收发送端的数据，并显示出来
            try {
                byte[] bytes = new byte[1024];
                DatagramPacket datagramPacket = new DatagramPacket(bytes,bytes.length);

                datagramSocket.receive(datagramPacket);

                String ip = datagramPacket.getAddress().getHostAddress();
                int port = datagramPacket.getPort();
                byte[] data = datagramPacket.getData();

                System.out.println(ip + ":" + port + "===>" + new String(data,0,datagramPacket.getLength()));

            }catch (Exception e){
                e.printStackTrace();
            }
        }


    }
}
